package org.light.framework.mvc;

import java.lang.reflect.Method;
import java.util.*;

import org.light.framework.mvc.annotation.Action;
import org.light.framework.util.ArrayUtil;
import org.light.framework.util.ClassUtil;
import org.light.framework.util.CollectionUtil;

/**
 * MVC控制器工具类
 * 
 * @author de.cel
 *
 */
public final class ControllerHelper {

	private static final Map<String, Handler> ACTION_MAP = new HashMap<String, Handler>();

	static {

		Set<Class<?>> controllerClassSet = ClassUtil.getControllerClassSet();
		if (CollectionUtil.isNotEmpty(controllerClassSet)) {
			for (Class<?> controllerClass : controllerClassSet) {
				Method[] methods = controllerClass.getDeclaredMethods();
				if (ArrayUtil.isNotEmpty(methods)) {
					for (Method method : methods) {
						if (method.isAnnotationPresent(Action.class)) {

							// 获取方法上的Action注解信息
							Action action = method.getAnnotation(Action.class);
							String mapping = action.method().toString().toLowerCase() + action.value();
							Handler handler = new Handler(controllerClass, method);

							ACTION_MAP.put(mapping, handler);
						}
					}
				}
			}
		}
	}

	/**
	 * 获取Handler
	 * 
	 * @param requestMethod
	 * @param requestPath
	 * @return
	 */
	public static Handler getHandler(String requestMethod, String requestPath) {

		for (String key : ACTION_MAP.keySet()) {
			if (key.equals(requestMethod + requestPath)) {
				return ACTION_MAP.get(key);
			}
		}
		return null;
	}

}
